package com.ms.service.module.fish.test;

import java.nio.ByteBuffer;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ms.service.module.fish.message.FishMsgType;
import com.ms.service.module.fish.message.FishRequestWrap;
import com.xpec.c4.codec.CodecUtility;
import com.xpec.c4.service.message.NetMessage;

public class FishClientHandler extends SimpleChannelHandler {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
//		ctx.sendUpstream(e);
		// 执行登录
		FishClient.sendMsg(ctx, new ClientMsgWriter(FishMsgType.ACTION_100,ClientRobot.userName));
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) {
		if(!(event.getMessage() instanceof NetMessage)) return;
		NetMessage netMsg = (NetMessage) event.getMessage();
		byte[] bodyBytes = (byte[]) CodecUtility.decodeByte(netMsg.getMessageContentBytes());
		ByteBuffer msg = ByteBuffer.wrap(bodyBytes);
		
		int action = msg.getInt();
		if(logger.isInfoEnabled()){
			logger.info("收到服务端消息:{}", action);
		}
		try {
			switch (action) {
			case FishMsgType.ACTION_100:
				ClientRobot.action100(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_102:
				ClientRobot.action102(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_111:
				ClientRobot.action111(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_113:
				ClientRobot.action113(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_112:
				ClientRobot.action112(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_118:
				ClientRobot.action118(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_200:
				ClientRobot.action200(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_201:
				ClientRobot.action201(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_202:
				ClientRobot.action202(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_203:
				ClientRobot.action203(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_204:
				ClientRobot.action204(ctx,new FishRequestWrap(msg));
				break;
			case FishMsgType.ACTION_205:
				ClientRobot.action205(ctx,new FishRequestWrap(msg));
				break;

			default:
				break;
			}
			
		} catch (Exception e) {
			logger.error("执行逻辑异常", e);
		}
	}

	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		logger.error("连接异常", e.getCause());
		e.getChannel().close();
	}
	
}
